package com.kasax.skinchange

import android.content.Context
import android.util.TypedValue

/**
 * 使用obtainStyledAttributes获取属性值
 * 获取主题属性的资源id
 */
fun getThemeColor(context: Context, attr: Int, defaultColor: Int): Int {
    val obtainStyleAttrs = context.theme.obtainStyledAttributes(intArrayOf(attr))
    // 创建数组
    val redIds = IntArray(obtainStyleAttrs.indexCount)
    for (i in 0 until obtainStyleAttrs.indexCount) {
        val type = obtainStyleAttrs.getType(i)
        redIds[i] =
            if (type >= TypedValue.TYPE_FIRST_COLOR_INT && type <= TypedValue.TYPE_LAST_COLOR_INT) {
                obtainStyleAttrs.getColor(i, defaultColor)
            } else {
                defaultColor
            }
    }
    obtainStyleAttrs.recycle()
    return redIds[0]
}

/**
 * 使用TypedValue获取
 * 获取主题属性的资源id
 */
fun getThemeColor2(context: Context, attr: Int, defaultColor: Int): Int {
    val typedValue = TypedValue()
    val success = context.theme.resolveAttribute(
        attr,
        typedValue,
        true
    )
    return if (success) {
        if (typedValue.type >= TypedValue.TYPE_FIRST_COLOR_INT && typedValue.type <= TypedValue.TYPE_LAST_COLOR_INT) {
            typedValue.data
        } else {
            defaultColor
        }
    } else {

        defaultColor
    }
}